import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

const Layout = () => import( '@/views/Layout')
const Home = () => import( '@/views/home/index')

import TopCategory from '@/views/category/index'
import SubCategory from '@/views/category/sub'
import Goods from '@/views/goods/index'
import Login from '@/views/login/index'
import LoginCallback from '@/views/login/callback'
import Cart from '@/views/cart/index'
import Checkout from '@/views/member/pay/checkout'
import PayIndex from '@/views/member/pay/index'
import PayResult from '@/views/member/pay/result'
import MemberLayout from '@/views/member/Layout'
import MemberHome from '@/views/member/home/index'
import MemberOrder from '@/views/member/order/index'


Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Layout',
        component: Layout,
        children: [
            {path: '/', component: Home},
            {path: '/category/:id', component: TopCategory},
            {path: '/category/sub/:id', component: SubCategory},
            {path: '/product/:id', component: Goods},
            {path: '/cart', component: Cart},
            {path: '/member/checkout', component: Checkout},
            {path: '/member/pay', component: PayIndex},
            {path: '/pay/callback', component: PayResult},
            {
                path: '/member', name: 'MemberLayout', component: MemberLayout,
                children: [
                    {path: '/member', component: MemberHome},
                    {path: '/member/order', component: MemberOrder}
                ]
            },
        ]
    },
    {path: '/login', component: Login},
    {path: '/login/callback', component: LoginCallback},

]

const router = new VueRouter({
    // mode: 'history',
    base: process.env.BASE_URL,
    routes,
    scrollBehavior() {
        return {x: 0, y: 0}
    }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
    // 需要登录的路由：地址是以 /member 开头
    if (!store.getters.token && to.path.startsWith('/member')) {
        return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
    }
    next()
})

export default router
